package api

import (
	"api-client/handler/request"
	pb "api-client/proto"
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"time"
)

func Add(c *gin.Context) {
	var req request.AddReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	s := pb.NewUserClient(conn)

	// Contact the server and print out its response.
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	s.Add(c, &pb.AddReq{
		Title: req.Title,
		Text:  req.Text,
	})
	c.JSON(http.StatusOK, gin.H{
		"msg":  "OK",
		"code": 200,
		"data": "add is success",
	})
}

func List(c *gin.Context) {
	var req request.ListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	s := pb.NewUserClient(conn)

	// Contact the server and print out its response.
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	list, _ := s.List(c, &pb.ListReq{
		Page: req.Page,
		Size: req.Size,
	})
	c.JSON(http.StatusOK, gin.H{
		"msg":  "OK",
		"code": 200,
		"data": list,
	})
}
